
import os
import subprocess
import shutil

basedir = os.path.dirname(__file__)
gens = [{
        'protos': [
            'common.proto',
        ],
        'cpp': '../../C++/proto/src',
        'java': '../../Java/proto/src/main/java',
        'cs': '../../C#/AnB/AnB/Proto/Common.cs',
    }]

osname = os.name
nt = osname == 'nt'
if nt:
    print("processing")
    protoc = os.path.join(basedir, "bin", "protoc.exe")
    protonet = os.path.join(basedir, "bin", "protobuf-net", "protogen.exe")
else:
    print("unsupported platform " + osname)
    exit(-1)

def ensure_dir(d):
    try:
        os.makedirs(d)
    except:
        pass

tmpdir = os.path.join(basedir, 'tmp')
ensure_dir(tmpdir)

def save_file(path, text):
    f = open(path, 'w')
    try:
        f.write(text)
    finally:
        f.close()

cpp_dir = os.path.join(tmpdir, 'cpp')
ensure_dir(cpp_dir)
java_dir = os.path.join(tmpdir, 'java')
ensure_dir(java_dir)
cs_dir = os.path.join(tmpdir, 'cs')
ensure_dir(cs_dir)


for gen in gens:
    cpp_cmd  = [protoc, '--proto_path=' + cpp_dir , '--cpp_out='  + os.path.join(basedir, gen['cpp' ])]
    java_cmd = [protoc, '--proto_path=' + java_dir, '--java_out=' + os.path.join(basedir, gen['java'])]
    cs_cmd   = [protonet]

    for proto in gen['protos']:
        protofile = open(os.path.join(basedir, proto), 'r')
        prototext = protofile.read()
        protofile.close()

        # C++
        tmp = os.path.join(cpp_dir, proto)
        save_file(tmp, prototext.replace('//[candidate C++] ', ''))
        cpp_cmd.append(tmp)

        # Java
        tmp = os.path.join(java_dir, proto)
        save_file(tmp, prototext.replace('//[candidate C++] ', ''))
        java_cmd.append(tmp)

        # C#
        tmp = os.path.join(cs_dir, proto)
        save_file(tmp, prototext.replace('//[candidate C#] ', ''))
        cs_cmd.append('-i:' + tmp)

    cs_cmd.append('-o:' + gen['cs'])

    print('C++')
    subprocess.call(cpp_cmd)
    print('Java')
    subprocess.call(java_cmd)
    if nt:
        print('C#')
        subprocess.call(cs_cmd)


